package net.oschina.victor.liu.lemon.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 权限认证授权
 * 
 * @author Victor
 *
 */
@Controller
public class AuthController {

	@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
	public String login() {
		Subject subject = SecurityUtils.getSubject();
		// 由于可能会不通过logout登出，此处判断是否有Principal存在 如果存在直接跳转到角色选择
		if (subject.getPrincipal() != null && subject.isAuthenticated()) {
			// SecurityUtils.getSubject().logout();
			System.out.println("已经登录了:" + subject.getPrincipal());
			// return "redirect:/manager/main"; // 指定跳转到的操作

			return "/index"; // 指定跳转到的操作
		}
		SecurityUtils.getSubject().logout();
		/*
		 * model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(null));
		 * LOGGER.info("Operator init login.jsp");
		 */
		// Comparator<String> c = (a, b) -> Integer.compare(a.length(),
		// b.length());
		// System.out.println("这里写的是啥，为了验证些啥呀" + c);
		return ("/login");
	}

	@RequestMapping(value = { "/", "login" }, method = RequestMethod.POST)
	public String login(HttpServletRequest request, Model model) {
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		String error = null;
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (exceptionClassName != null) {
			error = "其他错误：" + exceptionClassName;
		}
		model.addAttribute("error", error);
		return "login";
	}

	@RequestMapping("/index")
	public String index() {
		return "index";
	}
	/*
	 * public String logout(){ return "login"; }
	 */
	/*
	 * @RequestMapping(value = "/") public String index(HttpServletRequest
	 * request) { System.out.println(request.getServletPath());
	 * System.out.println("this a html"); return "index"; }
	 */
}
